package cn.iocoder.yudao.module.enterprise.controller.admin.reportdownload;

import cn.iocoder.yudao.module.enterprise.controller.admin.report.vo.ReportRespVO;
import cn.iocoder.yudao.module.enterprise.service.report.ReportService;
import cn.iocoder.yudao.module.enterprise.util.TranslateUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;

import org.springframework.validation.annotation.Validated;
import org.springframework.security.access.prepost.PreAuthorize;
import io.swagger.v3.oas.annotations.tags.Tag;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Operation;

import javax.validation.*;
import java.net.URLEncoder;
import java.io.IOException;
import java.nio.charset.StandardCharsets;

import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.pojo.CommonResult;

import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.framework.common.pojo.CommonResult.success;

import cn.iocoder.yudao.framework.excel.core.util.ExcelUtils;

import cn.iocoder.yudao.framework.operatelog.core.annotations.OperateLog;

import static cn.iocoder.yudao.framework.operatelog.core.enums.OperateTypeEnum.*;
import static cn.iocoder.yudao.module.enterprise.enums.ErrorCodeConstants.REPORT_LANGUAGE_NOT_EXISTS;

import cn.iocoder.yudao.module.enterprise.controller.admin.reportdownload.vo.*;
import cn.iocoder.yudao.module.enterprise.dal.dataobject.reportdownload.ReportDownloadDO;
import cn.iocoder.yudao.module.enterprise.convert.reportdownload.ReportDownloadConvert;
import cn.iocoder.yudao.module.enterprise.service.reportdownload.ReportDownloadService;

@Tag(name = "管理后台 - 报告下载")
@RestController
@RequestMapping("/enterprise/report-download")
@Validated
public class ReportDownloadController {

    @Resource
    private ReportDownloadService reportDownloadService;
    @Resource
    private ReportService reportService;

    @DeleteMapping("/delete")
    @Operation(summary = "删除报告下载")
    @Parameter(name = "id", description = "编号", required = true)
    @PreAuthorize("@ss.hasPermission('enterprise:report-download:delete')")
    public CommonResult<Boolean> deleteReportDownload(@RequestParam("id") Long id) {
        reportDownloadService.deleteReportDownload(id);
        return success(true);
    }

    @GetMapping("/get")
    @Operation(summary = "获得报告下载")
    @Parameter(name = "id", description = "编号", required = true, example = "1024")
    @PreAuthorize("@ss.hasPermission('enterprise:report-download:query')")
    public CommonResult<ReportDownloadRespVO> getReportDownload(@RequestParam("id") Long id) {
        ReportDownloadDO reportDownload = reportDownloadService.getReportDownload(id);
        return success(ReportDownloadConvert.INSTANCE.convert(reportDownload));
    }

    @GetMapping("/page")
    @Operation(summary = "获得报告下载分页")
    @PreAuthorize("@ss.hasPermission('enterprise:report-download:query')")
    public CommonResult<PageResult<ReportDownloadRespVO>> getReportDownloadPage(@Valid ReportDownloadPageReqVO pageVO) {
        PageResult<ReportDownloadDO> pageResult = reportDownloadService.getReportDownloadPage(pageVO);
        return success(ReportDownloadConvert.INSTANCE.convertPage(pageResult));
    }

    @GetMapping("/export-word")
    @Operation(summary = "导出核算报告")
    @PreAuthorize("@ss.hasPermission('enterprise:report-download:query')")
    public String exportReportDownload(@Valid ReportDownloadReqVO exportReqVO) throws IOException, InterruptedException {
        Integer language = exportReqVO.getLanguage();
        ReportDownloadDO reportDownload = reportDownloadService.getReportDownload(exportReqVO.getDownloadId());
        // 生成报告
        String fromLang = "zh";
        String toLang;
        String extend = "docx";
        String filePath = reportDownload.getReportUrl();
        String output = "docx";

        // 解析URL，获取文件名
        String[] urlSplit = reportDownload.getReportUrl().split("/");
        String fileName = urlSplit[urlSplit.length - 1];

        if (language == 1) {
            return reportDownload.getReportUrl();
        } else if (language == 2) {
            toLang = "en";
            fileName += "（英文版）";
        } else if (language == 3) {
            toLang = "kor";
            fileName += "（韩文版）";
        } else {
            throw exception(REPORT_LANGUAGE_NOT_EXISTS);
        }

        TranslateUtil translate = new TranslateUtil("20230625001723471", "tAUvXp7Op0HpmrDDUONo");
        // 创建报价服务
        String quoteRet = translate.createQuoteJob(fromLang, toLang, extend, fileName, filePath);
        System.out.println(quoteRet);
        JSONObject quoteRetJson = JSON.parseObject(quoteRet);
        String fileId = quoteRetJson.getJSONObject("data").getString("fileId");

        // 查询报价结果
        String queryQuoteRet = translate.queryQuote(fileId);
        System.out.println(queryQuoteRet);

        // 创建翻译服务
        String transRet = translate.createTransJob(fromLang, toLang, extend, fileName, filePath, output);
        System.out.println(transRet);
        JSONObject transRetJson = JSON.parseObject(transRet);
        String requestId = transRetJson.getJSONObject("data").getString("requestId");

        // 睡眠10秒
        Thread.sleep(10000);

        // 查询翻译结果
        String queryTransRet = translate.queryTrans(requestId);
        System.out.println(queryTransRet);
        JSONObject queryTransRetJson = JSON.parseObject(queryTransRet);
        return queryTransRetJson.getJSONObject("data").getString("fileSrcUrl");
    }

}
